/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.didi.virtualapk.databinding.annotationprocessor;

import com.didi.virtualapk.utils.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Set;
import java.util.regex.Pattern;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;

@SupportedAnnotationTypes({
    "android.databinding.BindingAdapter",
    "android.databinding.Untaggable",
    "android.databinding.BindingMethods",
    "android.databinding.BindingConversion",
    "android.databinding.BindingBuildInfo"}
)
/**
 * Parent annotation processor that dispatches sub steps to ensure execution order.
 * Use initProcessingSteps to add a new step.
 */
public class ProcessDataBinding extends AbstractProcessor {
    
    private static final String PARAM_MODULE_PKG = "android.databinding.modulePackage";
    private static final String DATA_BINDER_MAPPER_PACKAGE = "android.databinding";
    private static final String DATA_BINDER_MAPPER_CLASS_NAME = "DataBinderMapper";
    private static final String DATA_BINDER_MAPPER_FULL_NAME = DATA_BINDER_MAPPER_PACKAGE + "." + DATA_BINDER_MAPPER_CLASS_NAME;
    
    private String modulePackage;
    private FileObject fileObject;
    
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        for (Element element : roundEnv.getRootElements()) {
            if (element instanceof TypeElement) {
                TypeElement typeElement = (TypeElement) element;
                
                if (DATA_BINDER_MAPPER_FULL_NAME.contentEquals(typeElement.getQualifiedName())) {
                    readDataBinderMapper();
                }
            }
        }
    
        return false;
    }
    
    private void readDataBinderMapper() {
        BufferedReader reader = null;
        BufferedWriter writer = null;
        try {
            reader = new BufferedReader(fileObject.openReader(false));
    
            String className = DATA_BINDER_MAPPER_CLASS_NAME + "_" + modulePackage.replace('.', '_');
            JavaFileObject javaFileObject = processingEnv.getFiler().createSourceFile(DATA_BINDER_MAPPER_PACKAGE + "." + className);
            writer = new BufferedWriter(javaFileObject.openWriter());
            writer.write("// Generated by VirtualApk gradle plugin.");
            writer.newLine();
            
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(DATA_BINDER_MAPPER_CLASS_NAME)) {
                    if (line.contains("class")) {
                        line = line.replace(DATA_BINDER_MAPPER_CLASS_NAME, className + " extends " + DATA_BINDER_MAPPER_CLASS_NAME);
    
                    } else {
                        line = line.replace(DATA_BINDER_MAPPER_CLASS_NAME, className);
                    }
                }
                
                writer.write(line);
                writer.newLine();
            }
            
            Log.i("ProcessDataBinding", "Generated java source file: " + DATA_BINDER_MAPPER_PACKAGE + "." + className);
    
        } catch (Exception e) {
            e.printStackTrace();
        
        } finally {
            closeSafely(reader);
            closeSafely(writer);
        }
    }
    
    private static void closeSafely(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latest();
    }
    
    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
    
        modulePackage = processingEnv.getOptions().getOrDefault(PARAM_MODULE_PKG, "unknown");
        try {
            fileObject = processingEnv.getFiler().getResource(StandardLocation.SOURCE_OUTPUT, DATA_BINDER_MAPPER_PACKAGE, DATA_BINDER_MAPPER_CLASS_NAME + ".java");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}
